/**
 * 您可以将常用的方法、或系统 API，统一封装，暴露全局，以便各页面、组件调用，而无需 require / import.
 */
const prompt = require('@system.prompt')
const storage = require('@system.storage')
const router = require('@system.router')
const fetch = require('@system.fetch')
/**
 * 拼接 get url 和参数
 */
function queryString(url, query) {
  let str = []
  for (let key in query) {
    str.push(key + '=' + query[key])
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}
/**
 * toast
 * @param {*} message 
 * @param {*} duration 
 */
function showToast(message = '', duration = 0) {
  if (!message) return
  prompt.showToast({
    message: message,
    duration
  })
}
/**
 * 
 * @param {String} title 标题
 * @param {String} message 内容 
 * @param {Array} buttons 按钮的数组，按钮结构：{text:'text',color:'#333333'}，color 可选：buttons 的第 1 项为 positive button；buttons 的第 2 项（如果有）为 negative button；buttons 的第 3 项（如果有）为 neutral button。最多支持 3 个 button
 * @param {Function} callback 回调函数 
 */
function showDialog(title, message, buttons, callback) {
  prompt.showDialog({
    title,
    message,
    buttons,
    success: function (data) {
      callback(data)
    },
    cancel: function () {
      console.log('handling cancel')
    },
    fail: function (data, code) {
      console.log(`handling fail, code = ${code}`)
    }
  })
}
/**
 * 判断手机号码
 * @param {} data 
 */
function phone(data) {
  var mobile_mode = /^1[34578]\d{9}$/;
  if (!mobile_mode.test(data)) {
    return true;
  }
}

/**
 * 设置storage
 * @param {*} key 
 * @param {*} value 
 */
function setStorage(key, value) {
  storage.set({
    key,
    value: value,
    fail(data, code) {
      console.log(`setStorage fail, code = ${code}`)
    }
  })
}
/**
 * 清空所有的缓存
 * @returns 
 */
function clearStorage() {
  return new Promise((resolve, reject) => {
    storage.clear({
      success: function (data) {
        resolve()
      },
      fail: function (data, code) {
        reject()
      }
    })
  })
}
/**
 * 获取storage
 * @param {*} key 
 */
function getStorage(key) {
  return new Promise((resolve, reject) => {
    storage.get({
      key,
      success(data) {
        if (data) {
          resolve(data)
        } else {
          resolve('')
        }
      },
      fail(data, code) {
        console.log(`getStorage fail, code = ${code}`)
        reject({ data, code })
      }
    })
  })
}

/**
 * 删除缓存信息
 */
function deleteStorage(key) {
  storage.delete({
    key,
    success: function (data) {
      console.log('handling success')
    },
    fail: function (data, code) {
      console.log(`handling fail, code = ${code}`)
    }
  })
}

/**
 * route  push页面挑转
 */
function routetheUrl(url, params, clear = false) {
  router.push({
    uri: url,
    params: { ...params, clearRouter: clear }
  })
}
/**
 * route  Replace  页面挑转
 * @param {} url 
 * @param {*} params 
 */
function routeReplacetheUrl(url, params) {
  router.replace({
    uri: url,
    params: params
  })
}
/**
 * route  判断当前要跳转的路由是否为当前页面
 * @param {} url 
 * @param {*} params 
 */
function routeCheckUrl(url) {
  let routerList = router.getPages()
  console.log(`判断当前要跳转的路由是否为当前页面routeCheckUrl==>`, routerList)
  if (routerList[routerList.length - 1].path == url) {
    return true
  }
  return false
}
/**
 * route  检测当前页面数是否大于1
 */
function routeCheckPages() {
  let routerList = router.getPages()
  if (routerList.length > 1) {
    return true
  }
  return false
}
/**
 * 返回上一级
 */
function goBack() {
  router.back();
}
/**
 * 返回指定页面
 */
function goBackTo(path) {
  router.back({ path });
}
function clear() {
  router.clear()
}

/**
 *  //判断页面是否在栈内存里面存在，如果存在直接goback，否则跳转打开新路由
 */

function stacksRouter(path) {
  let routerList = []
  var stacks = router.getPages()
  stacks.forEach(item => {
    routerList.push(item.path)
  })
  //从数组中找到指定页面，没有则返回-1
  if (routerList.indexOf(path) != -1) {
    return true
  }
  return false
}

/**
 * 消息通知点击上报
 */
function pushMessageInfo(data) {
  $apis.example.pushMessage({
    pushId: data
  })
    .then(res => { })
    .catch(err => { })
}

/**
 * 手机返回键延迟2s
 * @param {number} startTimestamp  开始时间
 */
function backTime(startTimestamp, _this) {
  return new Date().getTime() - startTimestamp < _this.$app.$def.backTime
}

/**
 * 手机返回键延迟2s
 * @param {number} startTimestamp  开始时间
 * @param {Number} times  间隔差
 */
function backTimeCommon(startTimestamp, times) {
  return new Date().getTime() - startTimestamp < times
}

// 格式化倒计时 s->HH:mm:ss
function formatTime(time) {
  let hours = Math.floor(time / 3600)
  let minute = Math.floor(Math.floor(time % 3600) / 60)
  let second = time % 60
  hours = hours.toString().length === 1 ? `0${hours}` : hours
  minute = minute.toString().length === 1 ? `0${minute}` : minute
  second = second.toString().length === 1 ? `0${second}` : second
  return hours + ':' + minute + ':' + second
}
/* 
     * 截取指定字节长度的字符串 
     * 注：半角长度为1，全角长度为2
     * str:字符串 
     * len:截取长度
     * return: 截取后的字符串及是否截取的标记（扩展用）code=1 字符串截断   code=0  字符串未截断
     */
function cutStrByte(str, len) {
  //校验参数
  if (!str || !len) {
    return { "cutStr": "", "code": 0 };
  }
  var code = "1",// 默认返回code值，已截断
    strLen = str.length,// 原字符串长度
    cutStr;
  //如果字符串长度小于截取长度的一半,则返回全部字符串
  if (strLen <= len / 2) {
    cutStr = str;
    code = "0";
  } else {
    //遍历字符串
    var strByteCount = 0;
    for (var i = 0; i < strLen; i++) {
      //中文字符字节加2  否则加1
      strByteCount += getByteLen(str.charAt(i));
      //i从0开始 截断时大于len 只截断到第i个
      if (strByteCount > len) {
        cutStr = str.substring(0, i);
        break;
      } else if (strByteCount == len) {
        cutStr = str.substring(0, i + 1);
        break;
      }
    }
  }
  //cutstr为空，没有截断字符串
  if (!cutStr) {
    cutStr = str;
    code = "0";
  }
  return { "cutStr": cutStr, "code": code };
}

/**
* 获取字节长度，全角字符两个单位长度，半角字符1个单位长度
*/
function getByteLen(val) {
  var len = 0;
  if (!val) {
    return len;
  }
  for (var i = 0; i < val.length; i++) {
    if (!val[i]) {
      continue;
    }
    // 全角
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 2;
    } else {
      len += 1;
    }
  }
  return len;
};

/**
 * 判断时间捡个是否大于30分钟
 * @param {number} startTimestamp  开始时间
 * @param {Number} times  间隔差
 */
function adFreeTimeDifference(endTime) {
  let curTime = Date.parse(new Date());
  let minute = Math.floor((endTime - curTime) / 60000)
  console.log(`剩余看视频免广告时间======>${minute}`)
  return endTime > curTime ? true : false
}

/**
 * 计算当前时间戳和传入时间戳的差值 
 * @param {Number} timestamp 传入onShow记录的时间戳 
 * @return 单位 s
 */
function pageTimeCompute(timestamp) {
  let seconds = 0
  let cruTiemstamp = new Date().getTime()
  if (cruTiemstamp > timestamp) {
    seconds = Math.ceil((cruTiemstamp - timestamp) / 1000)
  }
  return seconds
}

/**
  * 截取字符串
  * @param {String} str 截取的字符串
  * @param {Number} n 截取的长度
  */
function cutStr(str, n) {
  var strArr = [];
  for (var i = 0, l = str.length; i < l / n; i++) {
    var a = str.slice(n * i, n * (i + 1));
    strArr.push(a);
  }
  return strArr;
}

/**
 * 根据弹窗code获取场景code
 * @param {String} code 
 * @param {Object} pageDetail
 */
function getPopSceneCodeByPopCode(code, pageDetail) {
  let sceneCode = ''
  switch (code) {
    case 'box':
      sceneCode = "AD_POP_BOX"
      break
    case 'award':
      sceneCode = "AD_POP_COIN"
      break
    case 'getway':
      sceneCode = "AD_POP_GETWAY"
      break
    case 'novelrecommend':
      sceneCode = "AD_POP_NOVEL"
      break
    case 'singlenovelrecommend':
      sceneCode = "AD_POP_SINGLE_NOVEL"
      break
    case 'vip':
      sceneCode = "AD_POP_VIP"
      break
    case 'back':
      if (pageDetail.pageCode == 'READ_WELFARE') {
        sceneCode = "AD_POP_WELFARE_BACK_POP"
      } else if (pageDetail.pageCode == 'READ_READINFO') {
        sceneCode = "AD_POP_READINFO_BACK_POP"
      } else {
        sceneCode = "AD_POP_BACK"
      }
      break
    case 'backprompt':
      sceneCode = "AD_POP_BACK_PROMPT"
      break
    case 'exit':
      sceneCode = "AD_POP_EXIT"
      break
    case 'exitprompt':
      sceneCode = "AD_POP_EXIT_PROMPT"
      break
    case 'unlock':
      sceneCode = "AD_POP_UNLOCK"
      break
  }
  return sceneCode
}

//启动参数上报 只针对华为
function uploadHuaweiLaunchData(obj) {
  if (!obj) return
  let param = Object.assign({
    APIVersion: '0.6.0',
    rtype: 'huawei',
    pkg: 'com.momonotes.home'
  }, obj)
  console.log('启动参数===>', param)

  fetch.fetch({
    url: 'https://rpclusters.cn-beijing.log.aliyuncs.com/logstores/rpclusters/track.gif',
    method: 'get',
    data: param,
    success: (data) => {
      console.log("启动参数上报成功")
    },
    fail: (data, code) => {
      console.log("启动参数上报失败", data, code)
    }
  })
}
/**
 * 检测指定value 是否满足相应条件
 * @param {Number} curVal 设置的值
 * @param {Number} defalutVal 默认的值
 * @param {String} cond 条件 is 等于   not_is 不等于  less 小于 greater 大于
 * @returns {Boolean} res 
 */
function checkKeyValueConditionSatisfied(curVal, defalutVal, cond) {
  if (cond != 'is' && cond != 'not_is' && cond != 'less' && cond != 'greater') {
    console.log('function checkKeyValueConditionSatisfied’s param(cond) not included is or not_is or less or greater')
    return false
  }
  let res = false
  switch (cond) {
    case 'is':
      res = curVal == defalutVal
      break
    case 'not_is':
      res = curVal != defalutVal
      break
    case 'less':
      res = curVal < defalutVal
      break
    case 'greater':
      res = curVal > defalutVal
      break
  }
  return typeof res == 'boolean' ? res : false
}
/**
 * 生成一条带类型标记和时间标记的普通信息
 * @param {String} typeString log 类型 REPORT TACTICS AD DATA API
 * @param  {...any} param log数据
 */
function Log(typeString, ...param) {
  switch (typeString) {
    case 'REPORT':
      console.log.call(null, '%c [REPORT] ', 'background: #6fa; color: #000', ...param)
      break
    case 'TACTICS':
      console.log.call(null, '%c [API] ', 'background: #ff6eec; color: #fff', ...param)
      break
    case 'AD':
      console.log.call(null, '%c [AD] ', 'background: #ffe270; color: #000', ...param)
      break
    case 'DATA':
      console.log.call(null, '%c [DATA] ', 'background: #f33; color: #fff', ...param)
      break
    case 'API':
      console.log.call(null, '%c [AJAX] ', 'background: #ff983c; color: #fff', ...param)
      break
    case 'VIEW':
      console.log.call(null, '%c [VIEW] ', 'background: #4436ff; color: #fff', ...param)
      break
    default:
      console.log.call(null, '%c [LOG] ', 'background: #333; color: #fff', typeString, ...param)
      break
  }
}
//根据老渠道获取新版渠道链接
function getExchangeChannelId(oldId) {
  const channelIdList = new Map([
    ["1", "ttzn"], ["5", "ttzw"], ["6", "kszn"], ["3", "kszw"], ["2", "opzn"], ["9", "opzw"], ["11", "vvzn"], ["7", "vvzw"], ["10", "xmzn"],
    ["4", "xmzw"], ["12", "hwzn"], ["8", "hwzw"], ["13", "iqyzn"], ["14", "iqyzw"], ["15", "gdtzn"], ["16", "gdtzw"], ["17", "xigua"], ["18", "tths"],
    ["19", "zchc"], ["20", "djhc"], ["21", "qdhc"], ["22", "ceshi"], ["23", "wbzn"]
  ]);
  let newChannelId = channelIdList.get(`${oldId}`)
  LOG('getExchangeChannelId==========>', oldId, newChannelId)
  return newChannelId ? newChannelId : oldId
}
// 获取二级来源
function getSourceType() {
  LOG('getSourceType==========>', require('@system.app').getInfo())
  return require('@system.app').getInfo().source.type
}
// 获取三级来源
function getExtraScene() {
  let scene = require('@system.app').getInfo().source.extra.scene
  return scene ? scene : ''
}

export default {
  showToast,
  queryString,
  phone,
  setStorage,
  getStorage,
  routetheUrl,
  routeReplacetheUrl,
  goBack,
  goBackTo,
  clear,
  deleteStorage,
  pushMessageInfo,
  backTime,
  backTimeCommon,
  routeCheckUrl,
  formatTime,
  routeCheckPages,
  clearStorage,
  showDialog,
  cutStrByte,
  getByteLen,
  adFreeTimeDifference,
  pageTimeCompute,
  cutStr,
  stacksRouter,
  uploadHuaweiLaunchData,
  getPopSceneCodeByPopCode,
  checkKeyValueConditionSatisfied,
  Log,
  getExchangeChannelId,
  getSourceType,
  getExtraScene,
}
